import {createApp} from 'vue'
import {PhNotifyOpt,PhNotifyReturn} from './index.type'
import Notification from './notification.vue'
import Evt from 'ph-evt'
const instances:Array<InstanceType<typeof Notification>> = []

export default {
    notify(content:string,opt?:PhNotifyOpt):PhNotifyReturn{
        let ins:InstanceType<typeof Notification>|undefined = undefined ;
        const evt = new Evt()
        const 
            position = opt?.position||"right-bottom",
            offset = 14;
        const onClose = (man?:boolean)=>{
            const 
                inss = instances.filter(n=>n.position.startsWith(position)),
                idx = inss.findIndex((n)=>n===ins),
                ykey = position.split("-")[1];
            if(idx>-1&&ins){
                instances.splice(idx,1)
                for(let i=idx+1;i<inss.length;i++){
                    const cmpcss = getComputedStyle(inss[i].$el) as any
                    const y = parseInt(cmpcss[ykey])||0
                    inss[i].show(y-ins.$el.offsetHeight-offset+"px")
                }
            }
            evt.emit("close",man,opt)
        }
        const onClick = ()=>{
            evt.emit("click",opt)
        }
        const 
            option = Object.assign({
                position,
                title:"系统通知",
                closable:true,
                autoClose:false,
                type:"",
                onClose,
                onClick,
                content
            },opt),
            notification = createApp(Notification,option),
            dom = document.createElement("div");
        ins = notification.mount(dom) as InstanceType<typeof Notification>;

        document.body.appendChild(ins.$el as Node)
        
        const inss = instances.filter(n=>n.position.startsWith(option.position))
        let y = offset;
        inss.forEach(n=>y+=n.$el.offsetHeight+offset)
        if(y>document.documentElement.offsetHeight){
            const toClose = inss.filter(n=>n.autoClose)[0]
            setTimeout(()=>{toClose?.close()})
        }
        ins?.show(y+"px")
        instances.push(ins)
        return {
            click(fn:(...a:any[])=>void){
                evt.on("click",fn)
                return this
            },
            close(fn:(...a:any[])=>void){
                evt.on("close",fn)
                return this
            }
        }
    }
}